<template>
  <div>
    <Card>
      <tables ref="tables" editable searchable search-place="top" v-model="tableData" :columns="columns" @on-delete="handleDelete" />
      <Page  :total="dataCount" :page-size="pageSize" @on-change="changepage" @on-page-size-change="_nowPageSize"
            show-total show-sizer show-elevator/>
      <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为Csv文件</Button>

    </Card>
  </div>
</template>

<script>
import Tables from '_c/tables'
import { getRoleData, getRole2API, getRole2User, getRole2Menu } from '@/api/data'
import CryptoJS from '@/libs/jiami'
import expandRow from './role-expand.vue'

export default {
  name: 'role',
  components: {
    Tables,
    expandRow
  },
  data () {
    return {

      columns: [

        { title: '角色ID', key: 'id', sortable: true },
        { title: '角色编码', key: 'code', editable: true },
        { title: '角色名称', key: 'name', editable: true },
        { title: '角色状态', key: 'status', editable: true },
        { title: '创建时间',
          key: 'createTime',
          render: (h, params) => {
            return h('div',
              CryptoJS.formatDate(new Date(params.row.createTime), 'yyyy-MM-dd hh:mm')
            )
          } },
        { title: '更新时间',
          key: 'updateTime',
          render: (h, params) => {
            return h('div',
              CryptoJS.formatDate(new Date(params.row.updateTime), 'yyyy-MM-dd hh:mm')
            )
          } },
        {
          title: '角色关联',
          key: 'aaa',
          type: 'expand',
          render: (h, params) => {
            console.log('--------------渲染开始--------------')
            console.log(params.row)
            // 更新数据
            this.tableData.forEach(function (value, index) {
              if (params.row.id === value.id) {
                params.row = value
                console.log('--------------更新数据成功--------------')
              }
            })

            return h(expandRow, {
              props: {
                row: params.row
              }
            })
          }
        },
        {
          title: 'Handle',
          key: 'handle',
          options: ['delete'],
          button: [
            (h, params, vm) => {
              return h('Poptip', {
                props: {
                  confirm: true,
                  title: '你确定要删除吗?'
                },
                on: {
                  'on-ok': () => {
                    vm.$emit('on-delete', params)
                    vm.$emit('input', params.tableData.filter((item, index) => index !== params.row.initRowIndex))
                  }
                }
              }, [
                h('Button', '自定义删除')
              ])
            }
          ]
        }
      ],
      tableData: [],
      // 分页
      pageSize: 10, // 每页显示多少条
      dataCount: 0, // 总条数
      pageCurrent: 1// 当前页

    }
  },
  methods: {
    handleDelete (params) {
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    },
    // 点击，切换页面
    changepage (index) {
      // 需要显示开始数据的index,(因为数据是从0开始的，页码是从1开始的，需要-1)
      this.pageCurrent = index
      console.log('当前页：' + index)
      console.log('进入换页函数')
      getRoleData(this.pageCurrent, this.pageSize).then(res => {
        this.tableData = res.data.data.data.list
        this.dataCount = res.data.data.data.total
        console.log('-====================-')
      })
    },
    // 每页显示的数据条数
    _nowPageSize (index) {
      // 实时获取当前需要显示的条数
      this.pageSize = index
    }
  },
  mounted () {
    // 需要分页
    let currentPage = this.pageCurrent
    let pageSize = this.pageSize

    getRoleData(currentPage, pageSize).then(res => {
      this.tableData = res.data.data.data.list
      this.dataCount = res.data.data.data.total
      console.log('角色分页信息装载完毕')
      console.log('获取当前角色下相关信息')
      // 异步处理集合
      let ps = []
      console.log('---执行循环异步开始---')
      this.tableData.forEach(function (value, index) {
        // 获取角色ID
        let roleId = value.id
        let currentPage4Role = 1
        let pageSize4Role = 150
        let Role2API = []
        console.log('@@@')

        const p = getRole2API(roleId, currentPage4Role, pageSize4Role)
          .then(resR => {
            console.log('查询当前角色' + roleId + '下API信息')
            console.log(resR)
            console.log('-------++-------')

            Role2API = resR.data.data.data.list
            console.log('设置角色下API')
            value.Role2API = Role2API
            console.log('当前角色处理完毕')
            // arr数组中数据组织
            return getRole2User(roleId, currentPage4Role, pageSize4Role)
          }).then(resR => {
            console.log('查询当前角色' + roleId + '下User信息')
            console.log(resR)
            console.log('-------+++-------')

            console.log('设置角色下USER')
            value.Role2User = resR.data.data.data.list
            console.log('当前用户处理完毕')
            // arr数组中数据组织
            return getRole2Menu(roleId, currentPage4Role, pageSize4Role)
          }).then(resR => {
            console.log('查询当前角色' + roleId + '下User信息')
            console.log(resR)
            console.log('-------+++-+++------')

            console.log('设置角色下USER')
            value.Role2Menu = resR.data.data.data.list
            console.log('当前菜单处理完毕')
            // arr数组中数据组织
            return 'success'
          })
        ps[index] = p
      })
      console.log('---执行循环异步完毕---')
      console.log(ps)
      return Promise.all(ps)
    }).then(arr => {
      console.log('Promise.all成功啦')
      console.log(arr)
      console.log(this.tableData)
    })
  }
}
</script>

<style>

</style>
